// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#pragma once

#include <functional>
#include <memory>
#include <string>
#include <vector>

#include <turbo/utility/status.h>
#include <turbo/base/macros.h>

namespace nebula {

    class StopToken;

    struct StopSourceImpl;

    /// EXPERIMENTAL
    class TURBO_EXPORT StopSource {
    public:
        StopSource();

        ~StopSource();

        // Consumer API (the side that stops)
        void RequestStop();

        void RequestStop(turbo::Status error);

        // Async-signal-safe. TODO Deprecate this?
        void RequestStopFromSignal(int signum);

        StopToken token();

        // For internal use only
        void reset();

    protected:
        std::shared_ptr<StopSourceImpl> impl_;
    };

    /// EXPERIMENTAL
    class TURBO_EXPORT StopToken {
    public:
        // Public for Cython
        StopToken() {}

        explicit StopToken(std::shared_ptr<StopSourceImpl> impl) : impl_(std::move(impl)) {}

        // A trivial token that never propagates any stop request
        static StopToken unstoppable() { return StopToken(); }

        /// \brief Check if the stop source has been cancelled.
        ///
        /// Producers should call this method, whenever convenient, to check and
        /// see if they should stop producing early (i.e. have been cancelled).
        /// Failure to call this method often enough will lead to an unresponsive
        /// cancellation.
        ///
        /// This is part of the producer API (the side that gets asked to stop)
        /// This method is thread-safe
        ///
        /// \return An OK status if the stop source has not been cancelled or a
        ///         cancel error if the source has been cancelled.
        turbo::Status Poll() const;

        bool is_stop_requested() const;

    protected:
        std::shared_ptr<StopSourceImpl> impl_;
    };

    /// EXPERIMENTAL: Set a global StopSource that can receive signals
    ///
    /// The only allowed order of calls is the following:
    /// - SetSignalStopSource()
    /// - any number of pairs of (RegisterCancellingSignalHandler,
    ///   UnregisterCancellingSignalHandler) calls
    /// - ResetSignalStopSource()
    ///
    /// Beware that these settings are process-wide.  Typically, only one
    /// thread should call these APIs, even in a multithreaded setting.
    TURBO_EXPORT
    turbo::Result<StopSource *> SetSignalStopSource();

    /// EXPERIMENTAL: reset the global signal-receiving StopSource
    ///
    /// This will invalidate the pointer returned by SetSignalStopSource.
    TURBO_EXPORT
    void ResetSignalStopSource();

    /// EXPERIMENTAL: Register signal handler triggering the signal-receiving StopSource
    ///
    /// Note that those handlers are automatically un-registered in a fork()ed process,
    /// therefore the child process will need to call RegisterCancellingSignalHandler()
    /// if desired.
    TURBO_EXPORT
    turbo::Status RegisterCancellingSignalHandler(const std::vector<int> &signals);

    /// EXPERIMENTAL: Unregister signal handler set up by RegisterCancellingSignalHandler
    TURBO_EXPORT
    void UnregisterCancellingSignalHandler();

}  // namespace nebula
